package lium.lbs.lbsim.activity

import android.app.DownloadManager
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.webkit.*
import android.widget.FrameLayout
import com.lmlibrary.Constants
import lium.lbs.lbsim.utils.ToastUtils
import kotlinx.android.synthetic.main.activity_webview.*
import lium.lbs.lbsim.R
import java.net.URLDecoder

open class WebViewActivity : BaseActivity() {


    private var loadUrl: String? = null
    var webview: WebView? = null
    var webTitle: String? = null

    override fun getLayoutId(): Int { return R.layout.activity_webview  }
    override fun initView(savedInstanceState: Bundle?) {
        webTitle = intent.getStringExtra("title")
        loadUrl = intent.getStringExtra("url")

        webview = WebView(this)
        webViewContainnerFL.addView(webview, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT ))
        webview!!.clearCache(true)

        val settings = webview!!.getSettings()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webview!!.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
            val request = DownloadManager.Request(Uri.parse(url))
            var fileName = url.substring(url.lastIndexOf("/") + 1)
            fileName = URLDecoder.decode(fileName)
            request.setDestinationInExternalPublicDir(Constants.CACHE_DIR + "download/", fileName)
            request.setTitle(fileName)
            request.allowScanningByMediaScanner()// 设置可以被扫描到
            request.setVisibleInDownloadsUi(true)
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE or DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            var downloadId = -1L
            try {
                downloadId = downloadManager.enqueue(request)
                ToastUtils.showToast("开始下载...")
            } catch (e: Exception) {
                e.printStackTrace()
                ToastUtils.showToast("下载失败，正在通过浏览器下载..")
                val uri = Uri.parse(url)
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data = uri
                startActivity(intent)
                return@DownloadListener
            }
        })
        //webview!!.setWebViewClient(YangSuWebViewClient())
        webview!!.setWebChromeClient(YangSuWebChromeClient())
        settings.javaScriptEnabled = true
        settings.setSupportZoom(true)
        settings.displayZoomControls = false
        settings.builtInZoomControls = true
        settings.allowContentAccess = true
        settings.allowFileAccess = true
        settings.loadWithOverviewMode = true
        settings.cacheMode = WebSettings.LOAD_NO_CACHE
        settings.domStorageEnabled = true
        settings.databaseEnabled = true
        settings.textZoom = 100
        settings.useWideViewPort = true
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview!!.addJavascriptInterface(Game_Methods(), "YSClient")
        webview!!.loadUrl(loadUrl)
    }

    /**
     * 重写的WebChromeClient
     */
    private inner class YangSuWebChromeClient : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            progressBar!!.progress = newProgress
        }

        override fun onReceivedTitle(view: WebView, title: String) {
            super.onReceivedTitle(view, title)
            setTitleWithBack(if (webTitle == null) title else webTitle)
        }

    }

    fun onLoadFinish() {

    }

    public class Game_Methods {
        private var money: String? = null
        private var shareUrl: String? = null
        @JavascriptInterface
        fun onBack() {
        }
    }
    override fun getNetWorkData() {
    }
}